const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const session = require("express-session");
let sessionStore = require("express-mysql-session")(session);
const logger = require("morgan");

// const indexRouter = require("./routes/index");
// const usersRouter = require("./routes/users");

const app = express();

// 设置模板引擎
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(express.static(path.join(__dirname, "public")));

app.use(logger("dev"));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
var options = {
  host: "localhost",
  port: 3306,
  user: "session_test",
  password: "password",
  database: "session_test",
};

app.use(
  session({
    secret: "demo",
    resave: false,
    saveUninitialized: false,
    rolling: true, //自动续期
    cookie: {
      // secure: true  //secure https这样的情况才可以访问cookie
      httpOnly: true,
      maxAge: 5000,
    },
    store: new sessionStore({
      host: "localhost",
      port: 3306,
      user: "root",
      password: "root",
      database: "seed",
    }),
  })
);

// 捕获404并转发给错误处理程序
app.use((req, res, next) => {
  let _user = req.session.user;
  if (_user) {
    res.locals.user = _user;
  }
  next();
});

app.use("/", require("./routes/index"));
app.use("/user", require("./routes/user"));

// 错误处理器
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // 渲染错误页面
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
